//
//  VariableNameUtil.m
//  xsd2cocoa
//
//  Created by Uwe Pachler on 06.02.14.
//
//

#import "VariableNameUtil.h"

@implementation VariableNameUtil

static NSSet* reservedWords() {
	NSSet* reservedWordDict = nil;
	reservedWordDict = [NSSet setWithObjects:
		// objc keywords
		@"void",
		@"char",
		@"short",
		@"int",
		@"long",
		@"float",
		@"double",
		@"signed",
		@"unsigned",
		@"id",
		@"const",
		@"volatile",
		@"static",
		@"auto",
		@"in",
		@"out",
		@"inout",
		@"bycopy",
		@"byref",
		@"oneway",
		@"self",
		@"super",
		@"if",
		@"while",
		@"for",
		@"new",
		@"try",
		@"catch",
		
		// names of NSObject class methods taking no parameters;
		// properties could shadow (override) these methods
		// unintentionally
		@"init",
		@"alloc",
		@"dealloc",
		@"copy",
		@"mutableCopy",
		@"description",
		@"autoContentAccessingProxy",
		@"classForCoder",
		@"classForKeyedArchiver",
		@"finalize",
		
		// NSObject protocol method without parameters
		@"class",
		@"superclass",
		@"hash",
		@"self",
		@"debugDescription",
		@"isProxy",
		@"retain",
		@"release",
		@"autorelease",
		@"retainCount",
		@"zone",
		nil
	];
	
	return reservedWordDict;
}

static NSString* reservedWordPrefix = @"xml_";

+ (NSString*) variableNameForName:(NSString*)name {
    NSCharacterSet* illegalChars = [NSCharacterSet characterSetWithCharactersInString: @"-"];
    
    NSString* vName = name;
    NSRange range = [vName rangeOfCharacterFromSet: illegalChars];
    while(range.length > 0) {
        vName = [vName stringByReplacingCharactersInRange: range withString: @""];
        // range is now at next char
        vName = [vName stringByReplacingCharactersInRange: range withString:[[vName substringWithRange: range] uppercaseString]];
        
        range = [vName rangeOfCharacterFromSet: illegalChars];
    }
	
	if([reservedWords() containsObject:vName]) {
		vName = [reservedWordPrefix stringByAppendingString:vName];
	}
	
    return vName;

}

@end